var canvas = $("#id-canvas");
var ctx = canvas[0].getContext('2d');

//position status
var params = {
    board: {
        x: 350,
        y: 460,
    },

    ball: {
        r: 10,
        x: 400,
        y: 450,
    },
};

var moveLeft = false;
var moveRight = false;
var paused = false;

//drawBoard\
var board = new Board(ctx, 100, 20);
board.init(params.board.x, params.board.y);

//drawBall
var ball = new Ball(ctx, params.ball.r);
ball.init(params.ball.x, params.ball.y);

//drawBlockGrid

var layout = [[1,1,1,1,1,1,1,1,1,1,1,1,1,1],[0,1,1,1,1,1,0,0,1,1,1,1,1,0],[0,0,0,0,1,1,0,0,0,0,0,1,1,0]];
var blockGrid = new BlockGrid(ctx, layout);
blockGrid.init();


//watch the gameover and gamecomplete event.
$("body").on("gameover", function() {
    clearInterval(gameInterval);
});

//watch the keydown event
window.addEventListener("keydown", function(e) {
    if(e.key === "a") {
        console.log(moveLeft);
        moveLeft = true;
    } else if(e.key === "d") {
        moveRight = true;
    } else if(e.key === "w" && ball.fired === false) {
        ball.fired = true;
        ball.fire();

    }else {
        return;
    }
});

window.addEventListener("keyup", function(e) {
    if(e.key === "a") {
        moveLeft = false;
    } else if(e.key === "d") {
        moveRight = false;
    } else {
        return;
    }
});

//加暂停调试
window.addEventListener("keydown", function(e) {
    if(e.key === "p") {
        paused = !paused;
    }
});

//check the value of moveLeft and moveRight periodically.
var gameInterval = setInterval(function() {
    if(paused) return;

    if(moveLeft == true) {
        board.moveLeft();
    } else if(moveRight == true) {
        board.moveRight();
    }

    if(ball.fired) {
        ball.move();
    } 

    board.solveCollision(ball);
    blockGrid.solveCollision(ball);
    
    
    clear(ctx);

    update(blockGrid);
    update(board);
    update(ball);

}, 1000/1000);